<template>
  <div class="createPost-container">
    <el-form ref="lawForm" :model="lawForm" :rules="lawFormRules" class="form-container">
      <div class="createPost-main-container">
        <el-row>
          <el-col :span="24">
            <div class="postInfo-container">
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label-width="115px"
                    label="法律法规名称:"
                    prop="name"
                    class="postInfo-container-item"
                  >
                    <el-input placeholder="请输入法律法规名称" v-model="lawForm.name"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label-width="115px"
                    label="文号:"
                    prop="fileNo"
                    class="postInfo-container-item"
                  >
                    <el-input placeholder="请输入文号" v-model="lawForm.fileNo"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label-width="115px"
                    label="发文部门:"
                    prop="dispatchDepartment"
                    class="postInfo-container-item"
                  >
                    <el-input
                      placeholder="请输入发文部门"
                      v-model="lawForm.dispatchDepartment"
                      class="postInfo-container-item"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label-width="115px"
                    label="有效性:"
                    prop="effectiveness"
                    class="postInfo-container-item"
                  >
                    <el-select v-model="lawForm.effectiveness" placeholder="请选择有效性" clearable>
                      <el-option
                        v-for="(item) in lawsEffectivenessList"
                        :key="item.id"
                        :label="item.dictValue"
                        :value="item.id"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label-width="115px"
                    label="级别:"
                    prop="level"
                    class="postInfo-container-item"
                  >
                    <el-select v-model="lawForm.level" placeholder="请选择级别" clearable>
                      <el-option
                        v-for="(item) in lawsLevelList"
                        :key="item.id"
                        :label="item.dictValue"
                        :value="item.id"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item
                    label-width="115px"
                    label="专业类别"
                    prop="category"
                    class="postInfo-container-item"
                  >
                    <el-select
                      v-model="lawForm.category.id"
                      placeholder="请选择类别"
                      style="width: 300px"
                      ref="organizationTree"
                    >
                      <el-option
                        :value="lawForm.category.id"
                        :label="lawForm.category.name"
                        style="height:200px;overflow: auto;background-color:#fff"
                      >
                        <el-tree
                          ref="organizationTree"
                          :data="categoryList"
                          node-key="id"
                          :expand-on-click-node="false"
                          @node-click="handleCategoryNodeClick"
                          :props="defaultProps"
                        ></el-tree>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label-width="115px"
                    label="颁布时间:"
                    prop="promulgationDate"
                    class="postInfo-container-item"
                  >
                    <el-date-picker
                      v-model="lawForm.promulgationDate"
                      type="date"
                      value-format="yyyy/MM/dd"
                      placeholder="请输入颁布时间"
                      class="filter-item"
                    ></el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label-width="115px"
                    label="实施时间:"
                    prop="implementDate"
                    class="postInfo-container-item"
                  >
                    <el-date-picker
                      v-model="lawForm.implementDate"
                      type="date"
                      value-format="yyyy/MM/dd"
                      placeholder="请输入实施时间"
                      class="filter-item"
                    ></el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label-width="115px"
                    label="文件概要:"
                    prop="fileAbstract"
                    class="postInfo-container-item"
                  >
                    <el-input
                      placeholder="请输入文件概要"
                      v-model="lawForm.fileAbstract"
                      type="textarea"
                      :rows="6"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="!isWatch">
                <el-col :span="12">
                  <el-form-item label="法律法规上传:" class="postInfo-container-item" label-width="115px">
                    <el-upload
                      ref="lawUpload"
                      action="#"
                      :before-upload="beforeAvatarUpload"
                      :on-preview="handlePreview"
                      :on-remove="handleRemove"
                      :multiple="false"
                      :file-list="[this.lawForm.fileInfo]"
                      :http-request="httpRequest"
                      accept=".pdf, .PDF"
                      :on-exceed="handleExceed"
                      :limit="1"
                    >
                      <el-button size="small" type="primary">点击上传</el-button>
                      <div slot="tip" class="el-upload__tip">只能上传单个pdf文件</div>
                    </el-upload>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="isWatch">
                <el-col :span="24">
                  <el-form-item label="文件预览:" label-width="120px">
                    <el-button size="small" type="primary" @click="handlePdfReview">预览</el-button>
                  </el-form-item>
                  <el-form-item v-if="pdfShow">
                    <div class="pdf">
                      <el-button-group>
                        <el-button
                          size="small"
                          type="primary"
                          icon="el-icon-arrow-left"
                          @click.stop="prePage"
                        >上一页</el-button>
                        <el-button size="small" type="primary" @click.stop="nextPage">
                          下一页
                          <i class="el-icon-arrow-right el-icon--right"></i>
                        </el-button>
                      </el-button-group>
                      <el-tag type="info">页码:{{pageNum}}/{{pageTotalNum}}</el-tag>
                      <el-button size="small" type="primary" @click.stop="pdfPrintAll">全部打印</el-button>
                      <el-progress
                        type="circle"
                        :percentage="Math.round(this.loadedRatio*100,1)"
                        :width="40"
                      ></el-progress>
                    </div>
                    <pdf
                      ref="pdf"
                      :src="pdfUrl"
                      :page="pageNum"
                      :rotate="pageRotate"
                      @progress="loadedRatio = $event"
                      @page-loaded="pageLoaded($event)"
                      @num-pages="pageTotalNum=$event"
                      @error="pdfError($event)"
                      @link-clicked="page = $event"
                    ></pdf>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="24">
                  <el-form-item style="text-align: center;">
                    <el-button type="primary" @click="submit" v-if="!isWatch">保存</el-button>
                    <el-button @click="closeCurrentTag">关闭</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-form>
  </div>
</template>

<script>
// import { validURL, validUsername } from '@/utils/validate'
import { getBaseDicInfo } from '@/api/baseApi'
import { fetchLaw, addLaw, updateLaw } from '@/api/laws'
import pdf from 'vue-pdf'

export default {
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    isNew: {
      type: Boolean,
      default: false
    },
    isWatch: {
      type: Boolean,
      default: false
    }
  },
  created() {
    this.getLawsEffectivenessList()
    this.getLawsLevelList()
    this.getCategoryList()
    if (this.isEdit || this.isWatch) {
      const id = this.$route.params && this.$route.params.id
      this.fetchLawData(id)
    }
    this.tempRoute = Object.assign({}, this.$route)
  },
  components: {
    pdf
  },
  /**
   *  name           法律法规名
   *  pubdate        发布时间
   *  entryTime      生效时间
   *  issuedNumber   发文字号
   *  issueUnit      发布机关
   *  validity       有效性
   */
  data() {
    return {
      lawFormRules: {
        name: [{ required: true, trigger: 'blur' }],
        fileNo: [{ required: true, trigger: 'blur' }],
        dispatchDepartment: [{ required: true, trigger: 'blur' }],
        effectiveness: [{ required: true, trigger: 'blur' }],
        level: [{ required: true, trigger: 'blur' }],
        category: [{ required: true, trigger: 'blur' }],
        fileAbstract: [{ required: true, trigger: 'blur' }],
        promulgationDate: [{ required: true, trigger: 'blur' }],
        implementDate: [{ required: true, trigger: 'blur' }]
      },
      pdfShow: false,
      // pdfType: '',
      pdfUrl: '',
      pageNum: 1,
      pageTotalNum: 1,
      pageRotate: 0,
      // 加载进度
      loadedRatio: 0,
      curPageNum: 0,
      lawForm: {
        id: '',
        name: '',
        fileNo: '',
        dispatchDepartment: '',
        effectiveness: '',
        level: '',
        category: {
          id: '',
          name: ''
        },
        fileAbstract: '',
        promulgationDate: '',
        implementDate: '',
        file: '',
        fileInfo: ''
      },
      defaultProps: {
        children: 'children',
        label: 'dictValue'
      },
      lawsEffectivenessList: [],
      lawsLevelList: [],
      categoryList: []
    }
  },
  methods: {
    submit() {
      if (this.isNew) {
        //新增
        this.$refs.lawForm.validate((valid) => {
          if (valid) {
            // console.log('this.lawForm', this.lawForm)
            const formData = new FormData()
            formData.append('name', this.lawForm.name)
            formData.append('fileNo', this.lawForm.fileNo)
            formData.append(
              'dispatchDepartment',
              this.lawForm.dispatchDepartment
            )
            formData.append('effectiveness', this.lawForm.effectiveness)
            formData.append('level', this.lawForm.level)
            formData.append('category', this.lawForm.category.id)
            formData.append('fileAbstract', this.lawForm.fileAbstract)
            formData.append('promulgationDate', this.lawForm.promulgationDate)
            formData.append('implementDate', this.lawForm.implementDate)
            formData.append('file', this.lawForm.file)
            formData.append('state', 0) //在库
            addLaw({ formData }).then((res) => {
              if (res.success) {
                this.$notify({
                  title: '成功',
                  message: '新增法律法规成功',
                  type: 'success',
                  duration: 2000
                })
              } else {
                this.$notify({
                  title: '失败',
                  message: '新增法律法规失败',
                  type: 'error',
                  duration: 2000
                })
              }
            })
          } else {
            this.$notify({
              title: '失败',
              message: '法律法规验证失败',
              type: 'error',
              duration: 2000
            })
            return false
          }
        })
      } else if (this.isEdit) {
        //如果是编辑
        this.$refs.lawForm.validate((valid) => {
          if (valid) {
            // console.log('this.lawForm', this.lawForm)
            const formData = new FormData()
            formData.append('id', this.lawForm.id)
            formData.append('name', this.lawForm.name)
            formData.append('fileNo', this.lawForm.fileNo)
            formData.append(
              'dispatchDepartment',
              this.lawForm.dispatchDepartment
            )
            formData.append('effectiveness', this.lawForm.effectiveness)
            formData.append('level', this.lawForm.level)
            formData.append('category', this.lawForm.category.id)
            formData.append('fileAbstract', this.lawForm.fileAbstract)
            formData.append('promulgationDate', this.lawForm.promulgationDate)
            formData.append('implementDate', this.lawForm.implementDate)
            formData.append('file', this.lawForm.file)
            formData.append('state', 0) //在库
            updateLaw({ formData }).then((res) => {
              if (res.success) {
                this.$notify({
                  title: '成功',
                  message: '更新法律法规成功',
                  type: 'success',
                  duration: 2000
                })
              } else {
                this.$notify({
                  title: '失败',
                  message: '更新法律法规失败',
                  type: 'error',
                  duration: 2000
                })
              }
            })
          } else {
            this.$notify({
              title: '失败',
              message: '法律法规验证失败',
              type: 'error',
              duration: 2000
            })
            return false
          }
        })
      }
    },
    handleCategoryNodeClick(node) {
      // console.log(node, 'node')
      this.lawForm.category.id = node.id
      this.lawForm.category.name = node.dictValue
    },
    //获取法规有效性列表
    getLawsEffectivenessList() {
      getBaseDicInfo({ typeId: 7 }).then((response) => {
        this.lawsEffectivenessList = response.data
      })
    },
    //获取法规级别列表
    getLawsLevelList() {
      getBaseDicInfo({ typeId: 8 }).then((response) => {
        this.lawsLevelList = response.data
      })
    },
    //获取专业类别列表
    getCategoryList() {
      getBaseDicInfo({ typeId: 9 }).then((response) => {
        this.categoryList = response.data
      })
    },
    closeCurrentTag() {
      // 调用全局挂载的方法
      this.$store.dispatch('tagsView/delView', this.$route)
      // 返回上一步路由
      this.$router.go(-1)
    },
    getLawLevelsList() {
      //获取法规级别
      getBaseDicInfo({ typeId: 8 }).then((response) => {
        this.lawLevelsList = response.data
      })
    },
    getLawEffectsList() {
      //获取法规有效性
      getBaseDicInfo({ typeId: 7 }).then((response) => {
        this.lawEffectsList = response.data
      })
    },
    handlePreview(file) {
      window.open('/api/' + file.url)
    },
    // 上传之前的格式设置
    beforeAvatarUpload(file) {
      //图片上传前图片大小和类型判断
      const isPdf = file.type === 'application/pdf'
      // const isSize = file.size / 1024 / 1024 / 5 < 1
      if (!isPdf) {
        this.$message.error('上传法律法规文件只能是PDF格式！')
      }
      // if (!isSize) {
      //   this.$message.error('上传pdf文件大小不能超过5MB！')
      // }
      // return isPdf && isSize
      return isPdf
    },
    httpRequest(data) {
      this.lawForm.file = data.file
    },
    handleRemove(file, fileList) {
      this.lawForm.file = ''
    },
    prePage() {
      var p = this.pageNum
      p = p > 1 ? p - 1 : this.pageTotalNum
      this.pageNum = p
    },
    nextPage() {
      var p = this.pageNum
      p = p < this.pageTotalNum ? p + 1 : 1
      this.pageNum = p
    },
    pageLoaded(e) {
      this.curPageNum = e
    },
    pdfError(error) {
      console.error(error)
    },
    pdfPrintAll() {
      this.$refs.pdf.print()
    },
    handlePdfReview() {
      console.log(this.lawForm.fileInfo.url)

      this.pdfUrl = `/api/${this.lawForm.fileInfo.url}`
      this.pdfShow = !this.pdfShow
    },
    handleClick(row) {
      console.log(row)
    },

    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length +
          fileList.length} 个文件,请删除后再上传`
      )
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    fetchLawData(id) {
      fetchLaw(id)
        .then((response) => {
          this.lawForm.id = response.data.info.id
          this.lawForm.name = response.data.info.name
          this.lawForm.fileNo = response.data.info.fileNo
          this.lawForm.dispatchDepartment =
            response.data.info.dispatchDepartment
          this.lawForm.effectiveness = response.data.info.effectiveness
          this.lawForm.level = response.data.info.level
          this.lawForm.category.id = response.data.info.category
          this.lawForm.category.name = response.data.info.categoryName

          this.lawForm.fileAbstract = response.data.info.fileAbstract
          this.lawForm.promulgationDate = response.data.info.promulgationDate
          this.lawForm.implementDate = response.data.info.implementDate
          this.lawForm.fileInfo = response.data.file[0]
          // console.log('this.lawForm', this.lawForm)

          // set tagsview title
          this.setTagsViewTitle()

          // set page title
          this.setPageTitle()
        })
        .catch((err) => {
          console.log(err)
        })
    },
    setTagsViewTitle() {
      const title = this.isEdit ? '编辑' : '查看'
      const route = Object.assign({}, this.tempRoute, {
        title: `${title}-${this.lawForm.name}`
      })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    setPageTitle() {
      const title = '编辑'
      document.title = `${title} - ${this.lawForm.name}`
    }
  }
}
</script>

<style lang="scss" scoped>
.createPost-main-container {
  padding-left: 50px;
  padding-top: 30px;
}
.pdf {
  text-align: center;
}
// /deep/ .el-row {
//   display: flex;
//   flex-direction: row;
//   justify-content: space-between;
// }

// /deep/ .el-col {
//   width: 50%;
//   flex: 1;
// }

// /deep/ .el-input__suffix {
//   position: absolute;
//   right: 10%;
// }

// /deep/ .el-input__inner {
//   width: 90%;
//   flex: 1;
//   position: relative;
// }

// .name {
//   display: flex;
//   flex-direction: row;
//   justify-content: space-between;
// }

// .preBtn {
//   display: flex;
//   height: 32px;
//   padding: 0 15px;
//   border: 1px solid #eee;
//   border-radius: 5px;
//   align-items: center;
// }

// .uploadFile {
//   width: 50%;
//   display: flex;
//   flex-direction: row;
//   justify-content: flex-start;
//   align-items: center;
//   margin-right: 20px;
// }

// /deep/ .el-upload-list--text {
//   display: inline-block;
//   width: auto;
//   flex-wrap: wrap;
//   display: flex;
//   align-items: center;
// }

// /deep/ .el-upload__tip {
//   border: 1px solid #eee;
//   border-radius: 5px;
//   width: 40%;
//   margin-left: 10px;
// }

// /deep/ .el-upload-list__item {
//   margin: 0;
// }

// /deep/ .el-upload--text,
// .el-upload__tip {
//   display: inline-block;
//   margin-top: 0;
// }

// /deep/.el-upload {
//   align-self: end;
// }

// .btn {
//   height: 40px;
//   padding: 0 50px;
//   border: none;
//   border-radius: 8px;
//   background: rgb(128, 190, 231);
//   margin-left: 20px;
//   color: #fff;
// }

// .btnBox {
//   margin-top: 20px;
//   display: flex;
//   justify-content: flex-end;
// }

// .clear {
//   padding: 0;
//   margin: 0;
// }

// /deep/.el-form-item__content {
//   display: flex;
//   flex-direction: row;
//   align-items: center;
// }

// .select {
//   flex: 1;
// }

// .right {
//   margin-right: -4.5%;
// }

// .input {
//   width: 89.8%;
//   flex: 1;
//   height: 40px;
// }

// .line {
//   height: 62px;
//   display: flex;
//   justify-content: space-between;
//   align-items: center;
//   width: 100%;
//   // overflow: hidden;
// }

// .form {
//   width: 100%;
//   margin-top: 10px;
// }

// .page {
//   width: 100%;
//   padding: 0 7.5%;
// }
</style>
